package com.cl.unipay4j.ali.transfer;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.request.AlipayFundTransOrderQueryRequest;
import com.alipay.api.response.AlipayFundTransOrderQueryResponse;
import com.cl.unipay4j.ali.AbstractAliPay;
import com.cl.unipay4j.core.IPayConfig;
import com.cl.unipay4j.core.Result;
import com.cl.unipay4j.core.transfer.ITransferQuery;
import com.cl.unipay4j.core.transfer.TransferQueryModel;
import com.cl.unipay4j.core.transfer.TransferResponse;
import com.cl.unipay4j.core.util.EnumUtil;
import com.cl.unipay4j.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝转账查询类
 *
 * @author  siashan
 * @since  v1.0.1
 **/
@Slf4j
public class AliPayTransferQuery extends AbstractAliPay implements ITransferQuery {
    public AliPayTransferQuery() {
    }

    public AliPayTransferQuery(IPayConfig payConfig) {
        super(payConfig);
    }

    /**
     * 查询企业付款结果
     *
     * @param model  转账查询实体类
     * @return  转账结果
     */
    @Override
    public Result<TransferResponse> execQuery(TransferQueryModel model) {
        AlipayFundTransOrderQueryRequest request = new AlipayFundTransOrderQueryRequest();
        request.setBizContent(JSON.toJSONString(wrapParam(model)));
        try {
            AlipayFundTransOrderQueryResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                return Result.tradeSuccess(wrapResponse(response));
            } else {
                return Result.tradeFail(response.getSubCode(), response.getSubMsg());
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return Result.exception();
    }


    /**
     * 包装转账结果
     *
     * @param r  支付宝转账结果
     * @return  转账结果
     */
    private TransferResponse wrapResponse(AlipayFundTransOrderQueryResponse r) {
        AliTransferState transferState = EnumUtil.getIEnum(AliTransferState.class, r.getStatus());
        TransferResponse response = new TransferResponse();
        response.setTransferState(transferState.getTransferState());
        response.setOutTradeNo(r.getOutBizNo());
        response.setTradeNo(r.getOrderId());
        response.setBody(JSON.toJSONString(r));
        return response;
    }

    /**
     * 包装查询参数
     *
     * @param model 查询实体
     * @return  查询参数
     */
    private Map<String, String> wrapParam(TransferQueryModel model) {
        Map<String, String> param = new HashMap<>();
        if (StrUtil.isNotEmpty(model.getOutTradeNo())) {
            param.put("out_biz_no", model.getOutTradeNo());
        }
        if (StrUtil.isNotEmpty(model.getTradeNo())) {
            param.put("order_id", model.getTradeNo());
        }
        return param;
    }
}
